<template>
  <div class="activity-management">
    <div class="page-header">
      <h2>活动管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="showCreateDialog">
          <el-icon><Plus /></el-icon> 发布活动
        </el-button>
      </div>
    </div>

    <el-card class="filter-card">
      <div class="filter-container">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="活动状态" clearable>
              <el-option label="全部" value="" />
              <el-option label="进行中" value="ACTIVE" />
              <el-option label="已结束" value="COMPLETED" />
              <el-option label="已取消" value="CANCELLED" />
            </el-select>
          </el-form-item>
          <el-form-item label="关键词">
            <el-input v-model="searchForm.keyword" placeholder="活动名称/地点" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon> 搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><Refresh /></el-icon> 重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card class="data-card">
      <div class="table-operations">
        <el-button :disabled="!hasSelected" type="danger" @click="handleBatchCancel">
          批量取消
        </el-button>
        <el-button :disabled="!hasSelected" type="success" @click="handleBatchExport">
          导出数据
        </el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="activitiesList"
        @selection-change="handleSelectionChange"
        border
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="活动名称" min-width="180">
          <template #default="{ row }">
            <div class="activity-title-cell">
              <div class="activity-image">
                <el-image 
                  :src="row.imageUrl || defaultImage" 
                  fit="cover"
                  @error="() => handleImageError(row)"
                />
              </div>
              <div class="activity-info">
                <span class="activity-title">{{ row.title }}</span>
                <el-tag 
                  size="small" 
                  :type="getStatusType(row)"
                >
                  {{ getStatusText(row) }}
                </el-tag>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="地点" min-width="120" />
        <el-table-column label="时间" min-width="180">
          <template #default="{ row }">
            <div>开始: {{ formatDateTime(row.startTime) }}</div>
            <div>结束: {{ formatDateTime(row.endTime) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="参与情况" width="120">
          <template #default="{ row }">
            <el-progress 
              :percentage="calculateParticipationPercentage(row)" 
              :status="row.currentParticipants >= row.maxParticipants ? 'success' : ''"
            />
            <div class="participation-text">
              {{ row.currentParticipants }}/{{ row.maxParticipants }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="平均评分" width="100">
          <template #default="{ row }">
            <el-rate 
              v-model="row.averageRating" 
              disabled 
              text-color="#ff9900"
              show-score
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button size="small" @click="viewActivityDetail(row.id)" type="primary" plain>
                <el-icon><View /></el-icon>
              </el-button>
              <el-button size="small" @click="viewRegistrations(row.id)" type="info" plain>
                <el-icon><List /></el-icon>
              </el-button>
              <el-button size="small" @click="editActivity(row)" type="warning" plain>
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button 
                size="small" 
                @click="cancelActivity(row)"
                :type="row.status === 'CANCELLED' ? 'success' : 'danger'" 
                plain
              >
                <el-icon>
                  <component :is="row.status === 'CANCELLED' ? 'Check' : 'Close'" />
                </el-icon>
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑活动对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditing ? '编辑活动' : '创建活动'"
      width="600px"
      :before-close="handleDialogClose"
    >
      <el-form 
        ref="activityFormRef"
        :model="activityForm"
        :rules="activityRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="活动名称" prop="title">
          <el-input v-model="activityForm.title" placeholder="请输入活动名称" />
        </el-form-item>
        
        <el-form-item label="活动描述" prop="description">
          <el-input 
            v-model="activityForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入活动描述"
          />
        </el-form-item>
        
        <el-form-item label="活动时间" prop="timeRange">
          <el-date-picker
            v-model="activityForm.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="dateShortcuts"
            value-format="YYYY-MM-DD HH:mm:ss"
            format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        
        <el-form-item label="活动地点" prop="location">
          <el-input v-model="activityForm.location" placeholder="请输入活动地点" />
        </el-form-item>
        
        <el-form-item label="最大人数" prop="maxParticipants">
          <el-input-number 
            v-model="activityForm.maxParticipants" 
            :min="1" 
            :max="1000"
            :step="1"
            step-strictly
          />
        </el-form-item>
        
        <el-form-item label="封面图片" prop="imageUrl">
          <el-input v-model="activityForm.imageUrl" placeholder="请输入图片URL">
            <template #append>
              <el-button @click="previewImage">预览</el-button>
            </template>
          </el-input>
          <div v-if="activityForm.imageUrl" class="image-preview">
            <el-image 
              :src="activityForm.imageUrl" 
              fit="cover"
              :preview-src-list="[activityForm.imageUrl]"
            />
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="submitActivityForm" :loading="submitting">
            {{ isEditing ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看报名记录对话框 -->
    <el-dialog
      v-model="registrationsDialogVisible"
      title="活动报名记录"
      width="900px"
    >
      <div v-loading="registrationsLoading">
        <div v-if="registrationsList.length === 0" class="empty-registrations">
          <el-empty description="暂无报名记录" />
        </div>
        <div v-else>
          <el-table :data="registrationsList" border style="width: 100%">
            <el-table-column prop="username" label="用户名" min-width="120" />
            <el-table-column prop="realName" label="真实姓名" min-width="120" />
            <el-table-column prop="email" label="邮箱" min-width="180" />
            <el-table-column prop="phone" label="电话" min-width="120" />
            <el-table-column prop="registrationTime" label="报名时间" min-width="180">
              <template #default="{ row }">
                {{ formatDateTime(row.registrationTime) }}
              </template>
            </el-table-column>
            <el-table-column label="出席状态" width="120">
              <template #default="{ row }">
                <el-switch
                  v-model="row.attended"
                  active-text="已出席"
                  inactive-text="未出席"
                  @change="updateAttendance(row)"
                />
              </template>
            </el-table-column>
          </el-table>
          
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="registrationPagination.page"
              v-model:page-size="registrationPagination.size"
              :page-sizes="[10, 20, 50]"
              layout="total, sizes, prev, pager, next"
              :total="registrationsTotal"
              @size-change="handleRegistrationSizeChange"
              @current-change="handleRegistrationCurrentChange"
            />
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getAllActivities,
  createActivity,
  updateActivity,
  cancelActivity as cancelActivityAPI,
  getActivityRegistrations,
  markAttendance
} from '@/api/club';
import { formatDateTime } from '@/utils/format';
import {
  Plus, Search, Refresh, View, Edit, Close, Check, List
} from '@element-plus/icons-vue';

const router = useRouter();
const defaultImage = 'https://via.placeholder.com/300x180?text=活动封面';

// 活动列表数据
const loading = ref(false);
const activitiesList = ref([]);
const total = ref(0);
const pagination = reactive({
  page: 1,
  size: 10,
  sortBy: 'startTime',
  direction: 'desc'
});

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: ''
});

// 选中的活动
const selectedActivities = ref([]);
const hasSelected = computed(() => selectedActivities.value.length > 0);

// 活动表单相关
const dialogVisible = ref(false);
const activityFormRef = ref(null);
const submitting = ref(false);
const isEditing = ref(false);
const activityForm = reactive({
  id: null,
  title: '',
  description: '',
  timeRange: [],
  location: '',
  maxParticipants: 30,
  imageUrl: ''
});

// 时间快捷选项
const dateShortcuts = [
  {
    text: '下周',
    value: () => {
      const start = new Date();
      start.setTime(start.getTime() + 3600 * 1000 * 24 * 7);
      start.setHours(9, 0, 0, 0);
      const end = new Date(start);
      end.setHours(18, 0, 0, 0);
      return [start, end];
    },
  },
  {
    text: '下个月',
    value: () => {
      const start = new Date();
      start.setMonth(start.getMonth() + 1);
      start.setDate(1);
      start.setHours(9, 0, 0, 0);
      const end = new Date(start);
      end.setHours(18, 0, 0, 0);
      return [start, end];
    },
  }
];

// 表单验证规则
const activityRules = {
  title: [
    { required: true, message: '请输入活动名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入活动描述', trigger: 'blur' },
    { min: 10, max: 2000, message: '长度在 10 到 2000 个字符', trigger: 'blur' }
  ],
  timeRange: [
    { 
      required: true, 
      message: '请选择活动时间', 
      trigger: 'change',
      type: 'array'
    }
  ],
  location: [
    { required: true, message: '请输入活动地点', trigger: 'blur' }
  ],
  maxParticipants: [
    { required: true, message: '请输入最大参与人数', trigger: 'blur' }
  ]
};

// 报名记录相关
const registrationsDialogVisible = ref(false);
const registrationsLoading = ref(false);
const registrationsList = ref([]);
const registrationsTotal = ref(0);
const currentActivityId = ref(null);
const registrationPagination = reactive({
  page: 1,
  size: 10
});

// 获取活动列表
const fetchActivities = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.page - 1,
      size: pagination.size,
      sortBy: pagination.sortBy,
      direction: pagination.direction,
      ...searchForm
    };
    
    const res = await getAllActivities(params);
    activitiesList.value = res.activities || [];
    total.value = res.total || 0;
  } catch (error) {
    console.error('获取活动列表失败', error);
    ElMessage.error('获取活动列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索活动
const handleSearch = () => {
  pagination.page = 1;
  fetchActivities();
};

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = '';
  searchForm.status = '';
  pagination.page = 1;
  fetchActivities();
};

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size;
  fetchActivities();
};

const handleCurrentChange = (page) => {
  pagination.page = page;
  fetchActivities();
};

// 选择行处理
const handleSelectionChange = (selection) => {
  selectedActivities.value = selection;
};

// 批量取消活动
const handleBatchCancel = async () => {
  if (selectedActivities.value.length === 0) return;
  
  try {
    await ElMessageBox.confirm(
      `确定要取消选中的 ${selectedActivities.value.length} 个活动吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    const promises = selectedActivities.value.map(activity => 
      cancelActivityAPI(activity.id)
    );
    
    await Promise.all(promises);
    ElMessage.success('批量取消活动成功');
    fetchActivities();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量取消活动失败', error);
      ElMessage.error('批量取消活动失败');
    }
  }
};

// 导出数据
const handleBatchExport = () => {
  ElMessage.info('导出功能开发中');
};

// 查看活动详情
const viewActivityDetail = (id) => {
  router.push(`/club/detail/${id}`);
};

// 查看活动报名记录
const viewRegistrations = async (id) => {
  currentActivityId.value = id;
  registrationsDialogVisible.value = true;
  registrationPagination.page = 1;
  registrationPagination.size = 10;
  await fetchRegistrations();
};

// 获取报名记录
const fetchRegistrations = async () => {
  if (!currentActivityId.value) return;
  
  registrationsLoading.value = true;
  try {
    const params = {
      page: registrationPagination.page - 1,
      size: registrationPagination.size
    };
    
    const res = await getActivityRegistrations(currentActivityId.value, params);
    registrationsList.value = res.registrations || [];
    registrationsTotal.value = res.total || 0;
  } catch (error) {
    console.error('获取报名记录失败', error);
    ElMessage.error('获取报名记录失败');
  } finally {
    registrationsLoading.value = false;
  }
};

// 报名记录分页处理
const handleRegistrationSizeChange = (size) => {
  registrationPagination.size = size;
  fetchRegistrations();
};

const handleRegistrationCurrentChange = (page) => {
  registrationPagination.page = page;
  fetchRegistrations();
};

// 更新出席状态
const updateAttendance = async (registration) => {
  try {
    await markAttendance(registration.id, registration.attended);
    ElMessage.success('出席状态更新成功');
  } catch (error) {
    console.error('更新出席状态失败', error);
    ElMessage.error('更新出席状态失败');
    registration.attended = !registration.attended; // 回滚UI状态
  }
};

// 编辑活动
const editActivity = (activity) => {
  isEditing.value = true;
  activityForm.id = activity.id;
  activityForm.title = activity.title;
  activityForm.description = activity.description;
  activityForm.timeRange = [activity.startTime, activity.endTime];
  activityForm.location = activity.location;
  activityForm.maxParticipants = activity.maxParticipants;
  activityForm.imageUrl = activity.imageUrl;
  dialogVisible.value = true;
};

// 取消活动
const cancelActivity = async (activity) => {
  const action = activity.status === 'CANCELLED' ? '恢复' : '取消';
  
  try {
    await ElMessageBox.confirm(
      `确定要${action}该活动吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await cancelActivityAPI(activity.id);
    ElMessage.success(`${action}活动成功`);
    fetchActivities();
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`${action}活动失败`, error);
      ElMessage.error(`${action}活动失败`);
    }
  }
};

// 显示创建对话框
const showCreateDialog = () => {
  isEditing.value = false;
  activityForm.id = null;
  activityForm.title = '';
  activityForm.description = '';
  activityForm.timeRange = [];
  activityForm.location = '';
  activityForm.maxParticipants = 30;
  activityForm.imageUrl = '';
  dialogVisible.value = true;
};

// 关闭对话框
const handleDialogClose = () => {
  activityFormRef.value?.resetFields();
  dialogVisible.value = false;
};

// 提交活动表单
const submitActivityForm = async () => {
  if (!activityFormRef.value) return;
  
  await activityFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    submitting.value = true;
    try {
      const formData = {
        title: activityForm.title,
        description: activityForm.description,
        startTime: activityForm.timeRange[0],
        endTime: activityForm.timeRange[1],
        location: activityForm.location,
        maxParticipants: activityForm.maxParticipants,
        imageUrl: activityForm.imageUrl || null
      };
      
      if (isEditing.value) {
        await updateActivity(activityForm.id, formData);
        ElMessage.success('更新活动成功');
      } else {
        await createActivity(formData);
        ElMessage.success('创建活动成功');
      }
      
      dialogVisible.value = false;
      fetchActivities();
    } catch (error) {
      console.error('提交活动失败', error);
      ElMessage.error('提交活动失败: ' + (error.message || '未知错误'));
    } finally {
      submitting.value = false;
    }
  });
};

// 预览图片
const previewImage = () => {
  if (!activityForm.imageUrl) {
    ElMessage.warning('请先输入图片URL');
    return;
  }
};

// 获取活动状态类型
const getStatusType = (activity) => {
  if (activity.status === 'CANCELLED') {
    return 'danger';
  }
  
  const now = new Date();
  const startTime = new Date(activity.startTime);
  const endTime = new Date(activity.endTime);
  
  if (endTime < now) {
    return 'info';  // 已结束
  } else if (startTime > now) {
    return 'primary';  // 未开始
  } else {
    return 'success';  // 进行中
  }
};

// 获取活动状态文本
const getStatusText = (activity) => {
  if (activity.status === 'CANCELLED') {
    return '已取消';
  }
  
  const now = new Date();
  const startTime = new Date(activity.startTime);
  const endTime = new Date(activity.endTime);
  
  if (endTime < now) {
    return '已结束';
  } else if (startTime > now) {
    return '未开始';
  } else {
    return '进行中';
  }
};

// 计算参与人数百分比
const calculateParticipationPercentage = (activity) => {
  if (!activity.maxParticipants) return 0;
  return Math.min(100, Math.round((activity.currentParticipants / activity.maxParticipants) * 100));
};

// 处理图片加载错误
const handleImageError = (activity) => {
  // 如果需要动态修改图片URL，可在此处理
};

onMounted(() => {
  fetchActivities();
});
</script>

<style scoped>
.activity-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 1.8rem;
  color: #303133;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  width: 100%;
}

.data-card {
  margin-bottom: 20px;
}

.table-operations {
  margin-bottom: 16px;
}

.activity-title-cell {
  display: flex;
  align-items: center;
}

.activity-image {
  width: 60px;
  height: 40px;
  margin-right: 10px;
  overflow: hidden;
  border-radius: 4px;
}

.activity-image .el-image {
  width: 100%;
  height: 100%;
}

.activity-info {
  display: flex;
  flex-direction: column;
}

.activity-title {
  margin-bottom: 4px;
  font-weight: bold;
}

.participation-text {
  text-align: center;
  margin-top: 5px;
  font-size: 12px;
  color: #606266;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.image-preview {
  margin-top: 10px;
  width: 200px;
  height: 120px;
  border-radius: 4px;
  overflow: hidden;
}

.image-preview .el-image {
  width: 100%;
  height: 100%;
}

.empty-registrations {
  padding: 30px;
  text-align: center;
}
</style> 